package com.keyancompany.zhongbaopingtai.fragment;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;

import com.alibaba.fastjson.JSONObject;
import com.keyancompany.zhongbaopingtai.Constants;
import com.keyancompany.zhongbaopingtai.R;
import com.keyancompany.zhongbaopingtai.activity.SelfPeopleInfoActivity;
import com.keyancompany.zhongbaopingtai.adapter.FindPeopleAdapter;
import com.keyancompany.zhongbaopingtai.adapter.MessageAdapter;
import com.keyancompany.zhongbaopingtai.adapter.SearchFriendsAdapter;
import com.keyancompany.zhongbaopingtai.api.TeamAPI;
import com.keyancompany.zhongbaopingtai.listener.IAsyncHttpResponseHandler;
import com.keyancompany.zhongbaopingtai.model.BaseModel;
import com.keyancompany.zhongbaopingtai.model.FriendModel;
import com.keyancompany.zhongbaopingtai.utils.IntentUtils;
import com.keyancompany.zhongbaopingtai.weight.IListView;

import java.util.List;

import butterknife.Bind;
import butterknife.OnItemClick;

/**
 * Created by firefox on 2016/5/31.
 */
public class FindItemPeopleFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, IAsyncHttpResponseHandler {

    @Bind(R.id.list_view)
    IListView listView;

    @Bind(R.id.find_swipe_layout)
    SwipeRefreshLayout swipeLayout;

    private FindPeopleAdapter mFindAdapter;

    private int currentPage = 1;

    private int total = 1;

    private boolean isFirst = true;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    swipeLayout.setRefreshing(false);
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * @param type
     * @return
     */
    public static FindItemPeopleFragment newInstance(int type) {
        FindItemPeopleFragment fragment = new FindItemPeopleFragment();
        Bundle args = new Bundle();
        args.putInt(FindFragment.TYPE, type);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getContentViewId() {
        return R.layout.fragment_find_item;
    }

    @Override
    public void setUpViews() {

        initSwipeLayout(swipeLayout);
        mFindAdapter = new FindPeopleAdapter(context);
        listView.setAdapter(mFindAdapter);
        swipeLayout.setOnRefreshListener(this);
        swipeLayout.post(new Thread(new Runnable() {

            @Override
            public void run() {
                swipeLayout.setRefreshing(true);
                onRefresh();
            }
        }));
        listView.setStateListener(new IListView.SwipeLayoutState() {
            @Override
            public boolean isRefresh() {
                return swipeLayout.isRefreshing();
            }

            @Override
            public boolean isLastPage() {
                return total == currentPage;
            }

            @Override
            public void requestNextPage() {
                requestTask(++currentPage);
            }
        });
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser && isFirst) {
            isFirst = false;

        }
    }

    public void requestTask(int currentPage) {
        TeamAPI.seller(null, null, "0", "" + currentPage, this, null);
    }


    @OnItemClick(R.id.list_view)
    public void listItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position < mFindAdapter.getCount()) {
            IntentUtils.startActivity(getActivity(), SelfPeopleInfoActivity.class, Constants.ITEM, mFindAdapter.getItem(position));
        }
    }


    @Override
    public void start(int type) {

    }


    @Override
    public void success(int type, String json) {
        mHandler.sendEmptyMessage(1);
//        Log.e("FindFragment", " ---- " + json);
        if (currentPage == 1) {
            mFindAdapter.clear();

        } else {

        }

        if (type == TeamAPI.SELLER_MARK) {
            //{"result":"success", "data":{"total":1,"current":1,
            // "list":[{"skills":"","sex":0,"tel":"18043624125","labels":",电磁学,宇宙化学,代数学","state":0,"headpic":null,"certification":0,
            // "username":"我是组织","rate":0.0,"PID_":"402881ee55e80f6c0155e84867f20048","email":null,"phoneverify":0,"mailverify":0,
            // "fields":",放射性计量学"}]},"msg":"加载成功"}
            try {
                BaseModel base = JSONObject.parseObject(json, BaseModel.class);
                Log.e("FindItemPeopleFragment", " ---- " + base.toString());
                if (base.isSuccess()) {
                    JSONObject object = JSONObject.parseObject(base.data);
                    currentPage = object.getInteger(Constants.CURRENT);
                    total = object.getInteger(Constants.TOTAL);
                    List<FriendModel> list = JSONObject.parseArray(object.getString("list"), FriendModel.class);
                    if (mFindAdapter == null) return;
                    listView.loadMoreFinish();
                    if (total == currentPage) {
                        listView.removeFooterView();
                    }
                    mFindAdapter.addAllAfter(list);
                    mFindAdapter.notifyDataSetChanged();
                }
            } catch (Exception e) {
                Log.e("FindFragment", " ---- " + e.toString());
            }
        }

    }

    @Override
    public void failed(String error) {
        mHandler.sendEmptyMessage(1);
    }

    @Override
    public void finish(int type) {

    }

    @Override
    public void onRefresh() {
        currentPage = 1;
        requestTask(currentPage);
    }
}
